package com.hmall.search.listen;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.hmall.common.client.ItemClient;
import com.hmall.common.dto.Item;
import com.hmall.search.constant.EsConstant;
import com.hmall.search.constant.MqConstants;
import com.hmall.search.pojo.ItemDoc;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * 商品消息监听
 *
 * @Author Eeyore
 * @Date 2022/8/12 11:56
 * @Description: 商品秀消息监听
 */
public class ItemListenr {

    @Autowired
    ItemClient itemClient;

    @Autowired
    RestHighLevelClient client;

    @RabbitListener(bindings = {
            @QueueBinding(
                    value = @Queue(name = MqConstants.ITEM_INSERT_QUEUE),
                    exchange = @Exchange(name = MqConstants.ITEM_DIRECT_EXCHANGE, type = ExchangeTypes.DIRECT),
                    key = MqConstants.ITEM_INSERT_KEY
            )
    })
    public void itemInsertProcess(String itemId) throws Exception {
        //上架操作
        Item item = itemClient.getById(itemId);
        ItemDoc itemDoc = new ItemDoc();
        ObjectMapper objectMapper = new ObjectMapper();
        String json = objectMapper.writeValueAsString(itemDoc);

        //向es中增加文件
        IndexRequest indexRequest = new IndexRequest(EsConstant.ITEM_INDEX);
        indexRequest.id(itemId);
        indexRequest.source(json, XContentType.JSON);
        client.index(indexRequest, RequestOptions.DEFAULT);

    }

    @RabbitListener(bindings = {
            @QueueBinding(
                    value = @Queue(name = MqConstants.ITEM_DELETE_QUEUE),
                    exchange = @Exchange(name = MqConstants.ITEM_DIRECT_EXCHANGE, type = ExchangeTypes.DIRECT),
                    key = MqConstants.ITEM_DELETE_KEY
            )
    })
    public void itemDeleteProcess(String itemId) throws Exception {
        //下架操作
        //向es中增加文件
        DeleteRequest deleteRequest = new DeleteRequest(EsConstant.ITEM_INDEX, itemId);
        client.delete(deleteRequest, RequestOptions.DEFAULT);
    }
}